package com.llt.system.service.qusetion.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llt.common.core.domain.R;
import com.llt.common.core.domain.TableDataInfo;
import com.llt.common.core.enums.ResultCode;
import com.llt.common.security.exception.ServiceException;
import com.llt.system.domain.question.dto.QuestionAddDTO;
import com.llt.system.domain.question.dto.QuestionDetailVO;
import com.llt.system.domain.question.dto.QuestionEditDTO;
import com.llt.system.domain.question.dto.QuestionQueryDTO;
import com.llt.system.domain.question.es.QuestionES;
import com.llt.system.domain.question.po.Question;
import com.llt.system.domain.question.vo.QuestionVO;
import com.llt.system.es.QuestionRepository;
import com.llt.system.manager.QuestionCacheManager;
import com.llt.system.mapper.question.QuestionMapper;
import com.llt.system.service.qusetion.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author llt
 * @since 2024-09-22
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO dto) {
        String excludeIdStr = dto.getExcludeIdStr();
        if (StrUtil.isNotEmpty(excludeIdStr)) {
            String[] excludeIds = excludeIdStr.split(";");
            Set<Long> excludeIdSet = Arrays.stream(excludeIds)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            dto.setExcludeIdSet(excludeIdSet);
        }
        // 1. 使用 PageHelper 进行分页查询
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<QuestionVO> list = questionMapper.selectQuestionList(dto);
        if (CollectionUtil.isEmpty(list)) {
            return TableDataInfo.empty();
        }

        // 2. 总条数,
        long total = new PageInfo<>(list).getTotal();

        return TableDataInfo.success(list, total);
    }

    @Override
    public R<Void> add(QuestionAddDTO dto) {
        // 1. 查是否已经存在
        boolean exists = this.lambdaQuery()
                .eq(Question::getTitle, dto.getTitle())
                .exists();

        if (exists) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }

        // 2. 将 dto 转为 po对象
        Question question = new Question();
        BeanUtil.copyProperties(dto, question);

        // 3. 保存
        boolean save = this.save(question);
        if (!save) {
            return R.fail();
        }

        // 4. 保存到 es
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question, questionES);
        questionRepository.save(questionES);

        // 5. 保存到 redis
        questionCacheManager.addCache(question.getQuestionId());
        return R.ok();
    }

    @Override
    public R<QuestionDetailVO> detail(Long questionId) {
        // 1. 根据 id 查询问题详情
        Question question = this.lambdaQuery()
                .eq(Question::getQuestionId, questionId)
                .one();
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        // 2. 转 vo 并返回
        QuestionDetailVO vo = new QuestionDetailVO();
        BeanUtil.copyProperties(question, vo);

        return R.ok(vo);
    }

    @Override
    public R<Void> edit(QuestionEditDTO dto) {
        // 1. dto 转 po
        Question po = new Question();
        BeanUtil.copyProperties(dto, po);
        // 2. 更新
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(po, questionES);
        questionRepository.save(questionES);

        return this.updateById(po) ? R.ok() : R.fail(ResultCode.FAILED.getCode(), "编辑失败");
    }

    @Override
    public R<Void> delete(Long questionId) {
        // 1. 判断题目是否存在(考虑到可能其他人删了, 浏览器没有刷新)
        boolean exists = this.lambdaQuery()
                .eq(Question::getQuestionId, questionId)
                .exists();
        if(!exists) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        // 2. 删除
        int delete = questionMapper.deleteById(questionId);
        questionRepository.deleteById(questionId);

        // 从 redis 删除
        questionCacheManager.deleteCache(questionId);

        return delete != 0 ? R.ok() : R.fail();
    }
}
